//
//  SearchResultCollectionView.m
//  YCSearchDemo
//
//  Created by huyuchen on 2018/3/3.
//  Copyright © 2018年 Hyc. All rights reserved.
//

#import "SearchResultCollectionView.h"

#define SearchResultDocumentPath [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]

#define kSearchResultHistoryCache [SearchResultDocumentPath stringByAppendingPathComponent:@"kSearchResultHistoryCache"]

@interface SearchResultCollectionView ()<UIGestureRecognizerDelegate>

@property (nonatomic, strong) NSMutableArray *historyArray;

@property (nonatomic, strong) UIColor *tagColor;

@property (nonatomic, strong) UIColor *tagBgColor;

@property (nonatomic, strong) UILabel *lastTagLabel;

@property (nonatomic, strong) UILabel *tipLabel;

@property (nonatomic, strong) UIButton *delBtn;

@property (nonatomic, strong) NSMutableArray *tagArray;

@end

@implementation SearchResultCollectionView

- (instancetype)initWithFrame:(CGRect)frame tagColor:(UIColor *)tagColor tagBgColor:(UIColor *)tagBgColor tagBlock:(BlockClickHotTag)clickBlock {
    if (self = [super initWithFrame:frame]) {
        self.userInteractionEnabled = YES;
        self.backgroundColor = [UIColor whiteColor];
        _tagBgColor = tagBgColor;
        _tagColor = tagColor;
        _clickBlock = clickBlock;
        
        self.historyArray = [NSKeyedUnarchiver unarchiveObjectWithFile:kSearchResultHistoryCache];
        if (!self.historyArray) {
            self.historyArray = [NSMutableArray arrayWithCapacity:0];
        }
        
        UILabel *tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 10, self.bounds.size.width, 20)];
        tipLabel.text = @"搜索记录";
        tipLabel.textColor = ColorDefalutGray;
        tipLabel.font = [UIFont boldSystemFontOfSize:15];
        _tipLabel = tipLabel;
        [self addSubview:tipLabel];
        
        UIButton *delBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [delBtn setImage:[UIImage imageNamed:@"home_goods_search_delete_ic"] forState:UIControlStateNormal];
        [delBtn setFrame:CGRectMake(CGRectGetWidth(frame)-40, 0, 40, 40)];
        [delBtn addTarget:self action:@selector(clickDelBtn:) forControlEvents:UIControlEventTouchUpInside];
//        delBtn.hidden = YES;
        _delBtn = delBtn;
        [self addSubview:delBtn];
        
        [self setResultKeyArr:self.historyArray];
    }
    return self;
}

- (void)clickDelBtn:(UIButton *)btn {
    [self clearHistoryCache];
}

- (void)cacheHistory {
    [NSKeyedArchiver archiveRootObject:self.historyArray toFile:kSearchResultHistoryCache];
}

- (void)clearHistoryCache {
    self.historyArray = [NSMutableArray arrayWithCapacity:0];
    [NSKeyedArchiver archiveRootObject:self.historyArray toFile:kSearchResultHistoryCache];
    [self setResultKeyArr:self.historyArray];
}

- (void)appendResultHistoryText:(NSString *)text {
    
    if ([self.historyArray containsObject:text]) {
        //如果之前存在，则排序置顶
        [self.historyArray removeObject:text];
        [self.historyArray insertObject:text atIndex:0];
    } else {
        //如果之前不存在，则插入置顶
        [self.historyArray insertObject:text atIndex:0];
    }
    
    [self cacheHistory];
    
    [self setResultKeyArr:self.historyArray];
}

- (void)setResultKeyArr:(NSArray *)resultKeyArr {
    
    //移除所有标签
    [self.tagArray makeObjectsPerformSelector:@selector(removeFromSuperview) withObject:nil];
    self.tagArray = [NSMutableArray array];
    
    //复原布局
    _lastTagLabel = nil;
    
    for (int i = 0 ; i< resultKeyArr.count ;i++) {
        
        NSString *textStr = resultKeyArr[i];
        
        UILabel *tag = [UILabel new];
        
        tag.text = textStr;
        
        CGSize tagSize = [textStr sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]}];
        tagSize.width += 10*2;
        tagSize.height += 5*2;
        
        if (i == 0) {
            //第一条，不存在lastTagLabel
            tag.frame = CGRectMake(15, CGRectGetMaxY(self.tipLabel.frame)+10, tagSize.width, tagSize.height);
        } else {
            
            if (CGRectGetMaxX(_lastTagLabel.frame)+
                15 +
                tagSize.width  > self.bounds.size.width-15) {
                //换行
                tag.frame = CGRectMake(15, CGRectGetMaxY(_lastTagLabel.frame)+10, tagSize.width, tagSize.height);
            }
            else {
                // 同一行
                tag.frame = CGRectMake(CGRectGetMaxX(_lastTagLabel.frame)+15, CGRectGetMinY(_lastTagLabel.frame), tagSize.width, tagSize.height);
                
            }
        }
        
        //配置文本
        [self configLabel:tag];
        
        [self addSubview:tag];
        
        [self.tagArray addObject:tag];
        
        _lastTagLabel = tag;
        
        //最后一个tag的时候赋值高度
        if (i == resultKeyArr.count-1) {
            CGRect tempFrame = self.frame;
            tempFrame.size.height = CGRectGetMaxY(_lastTagLabel.frame)+10;
            self.frame = tempFrame;
        }
    }

}

- (void)setBgColor:(UIColor *)bgColor {
    _bgColor = bgColor;
    self.backgroundColor = bgColor;
}

#pragma mark -- 文本属性设置
- (void)configLabel:(UILabel *)tag {
    tag.userInteractionEnabled = YES;
    
    if(_tagBgColor){
        //可以单一设置tag的颜色
        tag.backgroundColor = self.tagBgColor;
    }else{
        //tag颜色默认白色
        tag.backgroundColor = [UIColor whiteColor];
    }
    
    if (_tagColor) {
        tag.textColor = self.tagColor;
        tag.layer.borderColor = [self.tagColor CGColor];
    }
    else {
        tag.textColor = [UIColor lightGrayColor];
        tag.layer.borderColor = [[UIColor colorWithWhite:0.895 alpha:1.000] CGColor];
    }
    
    tag.textAlignment = NSTextAlignmentCenter;
    tag.font = [UIFont systemFontOfSize:14.f];
    tag.layer.cornerRadius = 10.0;
    tag.layer.borderWidth = 1.0;
    tag.clipsToBounds = YES;
    
    //给文本添加点击
    UITapGestureRecognizer *tapOne = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touchSubTagView:)];
    tapOne.delegate = self;
    tapOne.numberOfTapsRequired = 1.0;
    [tag addGestureRecognizer:tapOne];
}

#pragma mark -- 点击文本
-(void)touchSubTagView:(UITapGestureRecognizer*)tapOne
{
    UILabel *tag = (UILabel *)tapOne.view;
    if (_clickBlock) {
        _clickBlock(tag.text);
    }
}

- (NSMutableArray *)tagArray {
    if (!_tagArray) {
        _tagArray = [NSMutableArray array];
    }
    return _tagArray;
}
@end
